const fs = require('fs');

function findFile(filePath, index, callback) {
  fs.readdir(filePath, (err, files) => {
    if (err) {
      callback(err, null);
      return;
    }
    const searchFile = (files, index, callback) => {
      let foundFile = "";
      let i = 0;
      const checkNextFile = () => {
        if (i < files.length) {
          let item = files[i];
          let fullPath = filePath + (filePath.endsWith('/') ? '' : '/') + item;
          fs.stat(fullPath, (err, stats) => {
            if (err) {
              callback(err, null);
              return;
            }
            if (!stats.isDirectory()) {
              if (item === index || index === "") {
                foundFile = fullPath;
              }
              i++;
              checkNextFile();
            } else {
              findFile(fullPath, index, (err, result) => {
                if (err) {
                  callback(err, null);
                  return;
                }
                if (result) {
                  foundFile = result;
                }
                i++;
                checkNextFile();
              });
            }
          });
        } else {
          callback(null, foundFile);
        }
      };
      checkNextFile();
    };

    searchFile(files, index, callback);
  });
}

findFile("../", filename, (err, result) => {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});
